/*
 * Created by SharpDevelop.
 * User: michaelo
 * Date: 18/05/2005
 * Time: 19:08
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Drawing;
using System.Windows.Forms;
using Orz.LogManager.Config;
using System.Collections;
using System.Text.RegularExpressions;

namespace Orz.LogManager
{
	/// <summary>
	/// Description of EditLogset.
	/// </summary>
	public class EditLogsetForm : System.Windows.Forms.Form
	{
		private System.ComponentModel.IContainer components;
		private System.Windows.Forms.Button cmdDeleteLogFile;
		private System.Windows.Forms.Button cmdNewLogFile;
		private System.Windows.Forms.GroupBox grpLogFiles;
		private System.Windows.Forms.TextBox txtMaxCharsPerWindow;
		private System.Windows.Forms.Button cmdOK;
		private System.Windows.Forms.ColumnHeader colName;
		private System.Windows.Forms.ListView lvwFiles;
		private System.Windows.Forms.Button cmdCancel;
		private System.Windows.Forms.Button cmdCopy;
		private System.Windows.Forms.TextBox txtFileName;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.ColumnHeader colPath;
		private System.Windows.Forms.Button cmdEditLogFile;
		private System.Windows.Forms.TextBox txtDescription;
		private System.Windows.Forms.ImageList imageList1;
		
		
		private bool bWasCancelled_i;
		private LogsetWithFile working_i;
		private LogsetWithFile original_i;
		
		private HelpForm help_i;
		
		
		private EditLogsetForm()
		{
			// Should never be called
		}
		
		
		
		
		public EditLogsetForm (LogsetWithFile set_p)
		{
			InitializeComponent();
			original_i = set_p;
			
			// Make a backup of the working set before we start
			working_i = LogsetLoader.CloneLogsetWithFile (original_i);
			
			help_i = new HelpForm (this);
			
			PopulateFields();
		}
		
		
		
		
		public bool WasCancelled
		{
			get { return bWasCancelled_i; }
		}
		
		
		
		
		private void PopulateFields ()
		{
			txtFileName.Text = working_i.FileName;
			txtDescription.Text = working_i.Logset.description;
			txtMaxCharsPerWindow.Text = working_i.Logset.maxCharsPerWindow;			
			PopulateListview();
		}
		
		
		private void PopulateListview()
		{
			lvwFiles.Items.Clear();
			
			IEnumerator files = working_i.Logset.logfile.GetEnumerator();
			
			while (files.MoveNext())
			{
				logsetLogfile file = (logsetLogfile) files.Current;
				
				int iIconIndex = 0;
				
				if (LogsetLoader.isSSH(file))
				{
					iIconIndex = 2;
				}
				else if (LogsetLoader.isTelnet(file))
				{
					iIconIndex = 1;
				}								
				
				ListViewItem item = lvwFiles.Items.Add(file.name, iIconIndex);
				
				string sPath = file.path;
				
				if (iIconIndex > 0)  // i.e. is telnet or ssh
				{
					sPath = file.telnetHost + " : " + sPath;
				}
				
				item.SubItems.Add(sPath);
			}
			
			if (lvwFiles.Items.Count > 0)
			{
				lvwFiles.SelectedItems.Clear();
				lvwFiles.Items[0].Selected = true;				
			}							
			
			UpdateButtons();
		}
		
		
		
		
		
		private bool DoSave()
		{
			// First make sure the filename is a valid one, i.e. that it
			// only contains a-z, 0-1, dots, underscores, and spaces.
			
			if (! IsValidFileName (txtFileName.Text))
			{
				MessageBox.Show("That is not a valid filename!\n" +
				                "Filenames should only contain letters, numbers, dots, underscores and spaces.\n",
				                this.Text);
				
				return false;
			}
			
			
			if (! IsValidMaxChars (txtMaxCharsPerWindow.Text))
			{
				MessageBox.Show ("The maximum number of chars is nasty bad", this.Text);
				return false;
			}
			
			
			if (0 == lvwFiles.Items.Count)
			{
				MessageBox.Show("You need to specify at least one log file to view!\n" +
				                "Do this by clicking the 'New...' button and filling out the details on that form.",
				                this.Text);
				return false;
			}
			
			
			// Copy the values across
			working_i.FileName = AppendFileExtension(txtFileName.Text);
			working_i.Logset.description = txtDescription.Text;
			working_i.Logset.maxCharsPerWindow = txtMaxCharsPerWindow.Text;
			
			String sOriginalFileName = original_i.FileName;
			
			// Save the new logset
			LogsetLoader.SaveLogsetWithFile (working_i);
			
			// If this was an existing one that's been renamed then delete the old one
			if (null != sOriginalFileName  &&  sOriginalFileName.Length > 0  &&
			    !sOriginalFileName.Equals(working_i.FileName))
			{
				LogsetLoader.DeleteLogset(sOriginalFileName);
			}
			
			// Now copy the working logset details into the original one
			original_i.Logset = LogsetLoader.CloneLogset (working_i.Logset);
			original_i.FileName = working_i.FileName;
			
			MessageBox.Show ("Saved");
			
			return true;
		}
		
		
		
		private bool IsValidFileName (String sFileName_p)
		{
			Regex regex = new Regex("^[a-zA-Z0-9._ ]+$");
			
			return regex.IsMatch (sFileName_p);
		}
		
		
		private bool IsValidMaxChars (String sNumChars_p)
		{
			try
			{
				int iMaxChars = int.Parse(sNumChars_p);
				return iMaxChars > 0;
			}
			catch (Exception e)
			{
				return false;
			}
		}
		
		
		
		private string AppendFileExtension (String sFileName_p)
		{
			if (sFileName_p.EndsWith(".xml"))
			{
				return sFileName_p;
			}
			else
			{
				return sFileName_p + ".xml";
			}
		}
		
		
		
		private void UpdateButtons ()
		{
			bool areLogFiles = (lvwFiles.Items.Count > 0);
			cmdEditLogFile.Enabled = areLogFiles;
			cmdDeleteLogFile.Enabled = areLogFiles;
		}
		
		
		
		
		
		
		
		
		void CmdOKClick(object sender, System.EventArgs e)
		{
			if (DoSave())
			{
				bWasCancelled_i = false;
				this.Close();
			}
		}
		
		void CmdCancelClick(object sender, System.EventArgs e)
		{
			bWasCancelled_i = true;
			this.Close();
		}
		
		void CmdNewLogFileClick(object sender, System.EventArgs e)
		{
			logsetLogfile file = new logsetLogfile();
			
			
			if (lvwFiles.Items.Count > 0  &&  1 == lvwFiles.SelectedIndices.Count)
			{
				int iIndex = lvwFiles.SelectedIndices[0];
				logsetLogfile selected = (logsetLogfile) working_i.Logset.logfile[iIndex];
				
				if (DialogResult.Yes == MessageBox.Show ("Okey dokey!  Do you want to create a copy of the selected one (" + selected.name + ")?", "New log file reference", MessageBoxButtons.YesNo))
				{
					file = LogsetLoader.CloneLogfile(selected);
					file.name = null;
				}
			}
			
			
			EditLogFile f = new EditLogFile(file);
			f.ShowDialog();
			
			if (! f.WasCancelled)
			{
				AddNewLogfile(file);
			}
			
			PopulateListview();
		}
		
		
		private void AddNewLogfile(logsetLogfile file_p)
		{
			logsetLogfile[] origArray = working_i.Logset.logfile;
				
			logsetLogfile[] newArray = new logsetLogfile[origArray.Length+1];
			
			for (int i=0; i<origArray.Length; i++)
			{
				newArray[i] = origArray[i];
			}
			     
			newArray[newArray.Length-1] = file_p;
			
			working_i.Logset.logfile = newArray;
		}
		
		
		
		void CmdEditLogFileClick(object sender, System.EventArgs e)
		{
			if (0 == lvwFiles.Items.Count  ||  0 == lvwFiles.SelectedIndices.Count) return;
			
			int iIndex = lvwFiles.SelectedIndices[0];
			logsetLogfile file = working_i.Logset.logfile[iIndex];			
			
			EditLogFile f = new EditLogFile(file);
			f.ShowDialog();
			
			PopulateListview();
		}
		
		
		void LvwFilesDoubleClick(object sender, System.EventArgs e)
		{
			CmdEditLogFileClick(sender, e);
		}
		
		
		
		
		void CmdDeleteLogFileClick(object sender, System.EventArgs e)
		{
			if (0 == lvwFiles.Items.Count  ||  0 == lvwFiles.SelectedIndices.Count) return;
			
			int iIndex = lvwFiles.SelectedIndices[0];
			logsetLogfile file = working_i.Logset.logfile[iIndex];
			
			if (DialogResult.Yes == MessageBox.Show ("Are you sure you want to remove the entry for log file '" + file.name + "'?", this.Text, MessageBoxButtons.YesNo))
			{				
				logsetLogfile[] origArray = working_i.Logset.logfile;
					
				logsetLogfile[] newArray = new logsetLogfile[origArray.Length-1];
				
				for (int i=0; i<origArray.Length; i++)
				{					
					if (i < iIndex)
					{
						newArray[i] = origArray[i];
					}
					else if (i > iIndex)
					{
						newArray[i-1] = origArray[i];
					}
				}
								
				working_i.Logset.logfile = newArray;
				
				PopulateListview();
			}
		}
		
		
		
		
		
		#region Windows Forms Designer generated code
		/// <summary>
		/// This method is required for Windows Forms designer support.
		/// Do not change the method contents inside the source code editor. The Forms designer might
		/// not be able to load this method if it was changed manually.
		/// </summary>
		private void InitializeComponent() {
			this.components = new System.ComponentModel.Container();
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(EditLogsetForm));
			this.imageList1 = new System.Windows.Forms.ImageList(this.components);
			this.txtDescription = new System.Windows.Forms.TextBox();
			this.cmdEditLogFile = new System.Windows.Forms.Button();
			this.colPath = new System.Windows.Forms.ColumnHeader();
			this.label1 = new System.Windows.Forms.Label();
			this.label2 = new System.Windows.Forms.Label();
			this.label3 = new System.Windows.Forms.Label();
			this.txtFileName = new System.Windows.Forms.TextBox();
			this.cmdCopy = new System.Windows.Forms.Button();
			this.cmdCancel = new System.Windows.Forms.Button();
			this.lvwFiles = new System.Windows.Forms.ListView();
			this.colName = new System.Windows.Forms.ColumnHeader();
			this.cmdOK = new System.Windows.Forms.Button();
			this.txtMaxCharsPerWindow = new System.Windows.Forms.TextBox();
			this.grpLogFiles = new System.Windows.Forms.GroupBox();
			this.cmdNewLogFile = new System.Windows.Forms.Button();
			this.cmdDeleteLogFile = new System.Windows.Forms.Button();
			this.grpLogFiles.SuspendLayout();
			this.SuspendLayout();
			// 
			// imageList1
			// 
			this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
			this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
			this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
			// 
			// txtDescription
			// 
			this.txtDescription.Location = new System.Drawing.Point(160, 64);
			this.txtDescription.Name = "txtDescription";
			this.txtDescription.Size = new System.Drawing.Size(296, 20);
			this.txtDescription.TabIndex = 2;
			this.txtDescription.Tag = "An optional description of this configuration file, to help you keep track of whi" +
"ch is which!";
			this.txtDescription.Text = "";
			// 
			// cmdEditLogFile
			// 
			this.cmdEditLogFile.Location = new System.Drawing.Point(264, 216);
			this.cmdEditLogFile.Name = "cmdEditLogFile";
			this.cmdEditLogFile.TabIndex = 10;
			this.cmdEditLogFile.Tag = "Displays details of the selected log file and lets you make changes to it.";
			this.cmdEditLogFile.Text = "&Edit...";
			this.cmdEditLogFile.Click += new System.EventHandler(this.CmdEditLogFileClick);
			// 
			// colPath
			// 
			this.colPath.Text = "Path";
			this.colPath.Width = 400;
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(16, 32);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(136, 16);
			this.label1.TabIndex = 0;
			this.label1.Tag = "The XML file name used to store this configuration.  It should be relative to the" +
" Log Manager installation folder, and must be unique for each different configur" +
"ation.";
			this.label1.Text = "Configuration filename:";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(16, 64);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(100, 16);
			this.label2.TabIndex = 0;
			this.label2.Tag = "An optional description of this configuration file, to help you keep track of whi" +
"ch is which!";
			this.label2.Text = "Description:";
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(16, 96);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(144, 16);
			this.label3.TabIndex = 0;
			this.label3.Tag = @"If you leave Log Manager running for ages the windows will fill up and slow your machine down to a crawl.  You can set the number of KB of log data that will be displayed in each window, and when this limit is reached the lines at the top of the window will be truncated.";
			this.label3.Text = "Max size per window (KB):";
			// 
			// txtFileName
			// 
			this.txtFileName.Location = new System.Drawing.Point(160, 32);
			this.txtFileName.Name = "txtFileName";
			this.txtFileName.Size = new System.Drawing.Size(296, 20);
			this.txtFileName.TabIndex = 1;
			this.txtFileName.Tag = "The XML file name used to store this configuration.  It should be relative to the" +
" Log Manager installation folder, and must be unique for each different configur" +
"ation.  Note: this isn\'t the name of the log file you want to display!";
			this.txtFileName.Text = "";
			// 
			// cmdCopy
			// 
			this.cmdCopy.Location = new System.Drawing.Point(472, 112);
			this.cmdCopy.Name = "cmdCopy";
			this.cmdCopy.TabIndex = 8;
			this.cmdCopy.Text = "Copy from...";
			this.cmdCopy.Click += new System.EventHandler(this.CmdCopyClick);
			// 
			// cmdCancel
			// 
			this.cmdCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.cmdCancel.Location = new System.Drawing.Point(472, 48);
			this.cmdCancel.Name = "cmdCancel";
			this.cmdCancel.TabIndex = 6;
			this.cmdCancel.Tag = "Closes the dialog box, undoing any changes you may have made.";
			this.cmdCancel.Text = "&Cancel";
			this.cmdCancel.Click += new System.EventHandler(this.CmdCancelClick);
			// 
			// lvwFiles
			// 
			this.lvwFiles.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
						this.colName,
						this.colPath});
			this.lvwFiles.FullRowSelect = true;
			this.lvwFiles.HideSelection = false;
			this.lvwFiles.Location = new System.Drawing.Point(16, 24);
			this.lvwFiles.Name = "lvwFiles";
			this.lvwFiles.Size = new System.Drawing.Size(408, 184);
			this.lvwFiles.SmallImageList = this.imageList1;
			this.lvwFiles.TabIndex = 7;
			this.lvwFiles.Tag = "This list shows all the different log files that will be displayed as part of thi" +
"s configuration.  Use the \'New\', \'Edit\' and \'Delete\' buttons below to change the" +
"se.";
			this.lvwFiles.View = System.Windows.Forms.View.Details;
			this.lvwFiles.DoubleClick += new System.EventHandler(this.LvwFilesDoubleClick);
			// 
			// colName
			// 
			this.colName.Text = "Name";
			this.colName.Width = 170;
			// 
			// cmdOK
			// 
			this.cmdOK.Location = new System.Drawing.Point(472, 16);
			this.cmdOK.Name = "cmdOK";
			this.cmdOK.TabIndex = 6;
			this.cmdOK.Tag = "Closes the dialog box and saves any changes you have made.";
			this.cmdOK.Text = "&OK";
			this.cmdOK.Click += new System.EventHandler(this.CmdOKClick);
			// 
			// txtMaxCharsPerWindow
			// 
			this.txtMaxCharsPerWindow.Location = new System.Drawing.Point(160, 96);
			this.txtMaxCharsPerWindow.Name = "txtMaxCharsPerWindow";
			this.txtMaxCharsPerWindow.Size = new System.Drawing.Size(296, 20);
			this.txtMaxCharsPerWindow.TabIndex = 3;
			this.txtMaxCharsPerWindow.Tag = @"If you leave Log Manager running for ages the windows will fill up and slow your machine down to a crawl.  You can set the maximum number of KB of log data that will be displayed in each window, and when this limit is reached the lines at the top of the window will be truncated.";
			this.txtMaxCharsPerWindow.Text = "";
			// 
			// grpLogFiles
			// 
			this.grpLogFiles.Controls.Add(this.lvwFiles);
			this.grpLogFiles.Controls.Add(this.cmdNewLogFile);
			this.grpLogFiles.Controls.Add(this.cmdEditLogFile);
			this.grpLogFiles.Controls.Add(this.cmdDeleteLogFile);
			this.grpLogFiles.Location = new System.Drawing.Point(16, 136);
			this.grpLogFiles.Name = "grpLogFiles";
			this.grpLogFiles.Size = new System.Drawing.Size(440, 256);
			this.grpLogFiles.TabIndex = 7;
			this.grpLogFiles.TabStop = false;
			this.grpLogFiles.Text = "Individual log files to be displayed";
			// 
			// cmdNewLogFile
			// 
			this.cmdNewLogFile.Location = new System.Drawing.Point(184, 216);
			this.cmdNewLogFile.Name = "cmdNewLogFile";
			this.cmdNewLogFile.TabIndex = 11;
			this.cmdNewLogFile.Tag = "Allows you to associate a new log file with this configuration.";
			this.cmdNewLogFile.Text = "&Add...";
			this.cmdNewLogFile.Click += new System.EventHandler(this.CmdNewLogFileClick);
			// 
			// cmdDeleteLogFile
			// 
			this.cmdDeleteLogFile.Location = new System.Drawing.Point(344, 216);
			this.cmdDeleteLogFile.Name = "cmdDeleteLogFile";
			this.cmdDeleteLogFile.TabIndex = 9;
			this.cmdDeleteLogFile.Tag = "Removes the selected log file\'s details from this configuration so that it will n" +
"o longer be displayed.";
			this.cmdDeleteLogFile.Text = "&Delete";
			this.cmdDeleteLogFile.Click += new System.EventHandler(this.CmdDeleteLogFileClick);
			// 
			// EditLogsetForm
			// 
			this.AcceptButton = this.cmdOK;
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.CancelButton = this.cmdCancel;
			this.ClientSize = new System.Drawing.Size(560, 400);
			this.Controls.Add(this.cmdCopy);
			this.Controls.Add(this.grpLogFiles);
			this.Controls.Add(this.cmdOK);
			this.Controls.Add(this.txtMaxCharsPerWindow);
			this.Controls.Add(this.txtDescription);
			this.Controls.Add(this.txtFileName);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.cmdCancel);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "EditLogsetForm";
			this.ShowInTaskbar = false;
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
			this.Text = "Log Configuration Properties";
			this.grpLogFiles.ResumeLayout(false);
			this.ResumeLayout(false);
		}
		#endregion
		
		
		void CmdCopyClick(object sender, System.EventArgs e)
		{
			ImportLogFileForm f = new ImportLogFileForm();
			f.ShowDialog();
			
			if (null != f.LogFile)
			{
			 	logsetLogfile file = LogsetLoader.CloneLogfile(f.LogFile);
			 	AddNewLogfile(file);
			 	PopulateListview();
			}
		}
		
	}
}
